/*
 * converter.hpp
 *
 *  Created on: Apr 15, 2013
 *      Author: nick
 */

#ifndef CONVERTER_HPP_
#define CONVERTER_HPP_

#include <boost/spirit/include/qi.hpp>
#include "../hpp/logger.hpp"

typedef int DataType;

class ChunkConverter {
public:
	virtual void extract(std::string::const_iterator begin, std::string::const_iterator end, std::vector<DataType> & result) const = 0;
	virtual void collect(const std::vector<DataType> & dataToCollect, char* output) const = 0;
	virtual ~ChunkConverter() {}
};

class CSVConverter : public ChunkConverter {
public:
	CSVConverter() {}
	virtual void extract(std::string::const_iterator begin, std::string::const_iterator end, std::vector<DataType> & result) const {
		boost::spirit::qi::phrase_parse(begin, end, boost::spirit::qi::int_ % ',', boost::spirit::qi::space, result);
		if(begin != end) {
			std::ostringstream out;
			out << "Chunk is broken. Reading only " << result.size() << " elements.";
			Logging::warn(out.str());
		}
	}

	virtual void collect(const std::vector<DataType> & dataToCollect, char * output) const {
		std::ostringstream out;
		if (!dataToCollect.empty())	{
			std::copy(dataToCollect.begin(), dataToCollect.end()-1, std::ostream_iterator<int>(out, ","));
			out << dataToCollect.back();
		}
		memcpy((void*)output, (void*)(out.str().c_str()), out.str().size());
	}

	virtual ~CSVConverter() {}
};


#endif /* CONVERTER_HPP_ */
